<?php

require_once('news_task.inc.php');

class type_news{
	public $id;
	public $title;
	public $about;
	public $news_per_page;
	public $user_id;
	public $user_group;
	protected $perms;
	protected $old;
	private $task = false;
	
	/**
	 * Constructor
	 * 
	 * @author	Armin Borumand
	 */
	public function __construct(){
		global $lb;

		$this->id    = $lb['page']->type_id;
		
		$query	= 'SELECT * FROM #__news WHERE id = #';
		$params	= array(
					array($this->id, 'int')
					);
		$result = $lb['db']->query($query, $params);
		if($result['result'] && $result['num_of_rows'] > 0){
			$this->title 					= $result['rows'][0]['title'];
			$this->about 					= $result['rows'][0]['about'];
			$this->news_per_page				= $result['rows'][0]['news_per_page'];
			$this->user_id					= $result['rows'][0]['user_id'];
			$this->perms['who_send']			= $result['rows'][0]['who_send'];
			$this->perms['who_edit']			= $result['rows'][0]['who_edit'];
			$this->perms['who_confirm']			= $result['rows'][0]['who_confirm'];
			$this->perms['who_edit_comment_setting']	= $result['rows'][0]['who_edit_comment_setting'];
			$this->perms['who_comment']			= $result['rows'][0]['who_comment'];
			$this->perms['who_confirm_comment']		= $result['rows'][0]['who_confirm_comment'];
			$this->user_group 				= lb_group::user_group($this->user_id);
		}
	}

	/**
	 * generate and return title of page
	 * 
	 * @author	Armin Borumand
	 * @return 	string		page's title on success or false on failure
	 */
	public function get_title($id=false){
		global $lb;
		
		if($id === false){
			$id = $this->id;
		}
		
		$query = 'SELECT title FROM #__news WHERE id=#';
		
		$params = array (
				array ($id, 'int')
				);
			
		$result = $lb['db']->query($query, $params);
		
		// if page exist
		if($result['num_of_rows'] > 0){
			return $result['rows'][0]['title'];
		}else{
			return false;
		}
	}
	
	/**
	 * generate and return content of page
	 * 
	 * @author	Armin Borumand
	 * @param 	boolean		false means return page details and true means do procedure
	 * @return 	string		page's content
	 */
	public function get_content($freez=true){
		global $lb;

		if(!$freez){
			$query	= 'SELECT * FROM #__news WHERE id = #';
			$params	= array(
						array($this->id, 'int')
						);
						
			$result = $lb['db']->query($query, $params);
			if($result['result']){
				return $result['rows'][0];
			}else{
				return false;
			}
		}
		
		if(!$this->task){
			$this->task = new news_task($this);
		}
		
		if(isset($_GET['news_task'])){
			$task = trim($_GET['news_task']);
		}else{
			$task = 'index';
		}
		
		return array('item' => $task, 'content' => $this->task->$task());
	}

	/**
	 * Add a new page
	 *
	 * @author	Armin Borumand
	 * @param		array		page contents
	 * @param		bool/int	page id
	 * @return 	int			added page id
	 */
	public function add_page(&$arr, $id=false){
		global $lb;
		
		$_POST['title'] = lb_system::htmlspecialchars($_POST['title']);
		self::html_filter($_POST['about']);
		
		$query = 'INSERT INTO #__news (user_id, title, about, news_per_page, who_send, who_edit, who_confirm
									, who_edit_comment_setting, who_comment, who_confirm_comment)
							   VALUES (#, #, #, #, #, #, #, #, #, #)';
		$params = array(
					array($lb['user']->user_id		, 'int'),
					array($arr['title']			, 'string'),
					array($arr['about']			, 'string'),
					array($arr['news_per_page']		, 'int'),
					array($arr['who_send']			, 'string'),
					array($arr['who_edit']			, 'string'),
					array($arr['who_confirm']		, 'string'),
					array($arr['who_edit_comment_setting'], 'string'),
					array($arr['who_comment']		, 'string'),
					array($arr['who_confirm_comment']	,'string')
					);
					
		$result = $lb['db']->query($query, $params);

		if($result['result']){
			return $result['insert_id'];
		}else{
			return false;
		}
	}
	
	/**
	 * update edited page information in database
	 * 
	 * @author	Armin Borumand
	 * @param		array		page contents
	 * @param		bool/int	page id
	 * @return 	boolean	true on success or false on failure
	 */
	public function edit_page(&$arr, $backup=true){
		global $lb;
		
		if($backup){
			$this->backup();
		}
		
		$_POST['title'] = lb_system::htmlspecialchars($_POST['title']);
		self::html_filter($_POST['about']);

		$query = 'UPDATE #__news SET title = #, about = #, news_per_page = #, who_send = #, who_edit = #, who_confirm = #
					, who_edit_comment_setting = #,who_comment = #, who_confirm_comment = # 
					 WHERE id = #';
		$params = array(
					array($arr['title']			, 'string'),
					array($arr['about']			, 'string'),
					array($arr['news_per_page']		, 'int'),
					array($arr['who_send']			, 'string'),
					array($arr['who_edit']			, 'string'),
					array($arr['who_confirm']		, 'string'),
					array($arr['who_edit_comment_setting'], 'string'),
					array($arr['who_comment']		, 'string'),
					array($arr['who_confirm_comment']	,'string'),
					array($this->id				, 'int')
					);
		$result = $lb['db']->query($query, $params);

		if($result['result']){
			$this->title 					= $arr['title'];
			$this->about 					= $arr['about'];
			$this->news_per_page 				= $arr['news_per_page'];
			$this->perms['who_send']			= $arr['who_send'];
			$this->perms['who_edit']			= $arr['who_edit'];
			$this->perms['who_confirm']			= $arr['who_confirm'];
			$this->perms['who_edit_comment_setting']	= $arr['who_edit_comment_setting'];
			$this->perms['who_comment']			= $arr['who_comment'];
			$this->perms['who_confirm_comment']		= $arr['who_confirm_comment'];
			
			if(isset($arr['apply_previous']) && $arr['apply_previous'] == 'on'){
				$query = 'UPDATE #__news_store SET who_comment = #, who_confirm_comment = # WHERE news_id = #';
				$params = array(
							array($arr['who_comment']		, 'string'),
							array($arr['who_confirm_comment']	,'string'),
							array($this->id				, 'int')
							);
				$lb['db']->query($query, $params);
			}
			return true;
		}else{
			return false;
		}
	}
		
	/**
	 * Remove page
	 *
	 * @author	Armin Borumand
	 * @param	int		page type id to be removed (if false remove current page)	
	 * @return	boolean	true on success and false on failure
	 */
	public function remove_page($id = false){
		global $lb;
		
		if(!$id){
			$id = $this->id;
		}
		//Step1: remove current page stored news(delete from store,log,...)
		// Ba`dan :D
		
		//Step2: remove current page
		$query = 'DELETE FROM #__news WHERE id = #';
		$params = array(
						array($id, 'int')
					);
		$result = $lb['db']->query($query, $params);

		return $result['result'];
	}
	
	/**
	 * Store current news details in $this->old
	 *
	 * @access	private
	 * @author	Armin Borumand
	 * @return	boolean	true on success	and false on failure
	 */
	private function backup(){
		global $lb;
		
		$query	= 'SELECT * FROM #__news WHERE id = #';
		$params	= array(
					array($this->id, 'int')
					);
		if($result = $lb['db']->query($query, $params)){
			$this->old = $result['rows'][0];
			return true;
		}else{
			$this->old = false;
			return false;
		}
	}

	/**
	 * Restore old title and content in plugin database
	 *
	 * @author	Armin borumand
	 * @param	boolean	Add or edit
	 * @return	boolean	true on success and false on failure
	 */
	public function restore($add=false){
		global $lb;
		
		if($add === false){
			$result = $this->edit_page($this->old);
		}else{
			$result = $this->add_page($this->old, $this->id);
		}
		
		if($result){
			$arr['title'] = $this->old['title'];
			$this->old = array();
			return true;
		}else{
			return false;
		}
	}

	/**
	  * install this page type
	  * 
	  * @author	Armin Borumand
	  * @return	boolean		return true if successfull installed
	  */
	public function install(){
		global $lb;
		
		$queries = array (
		'CREATE TABLE `#__news` (
              `id` int(11) NOT NULL auto_increment,
              `user_id` int(11) NOT NULL default \'0\',
              `title` varchar(255) NOT NULL default \'\',
              `news_per_page` tinyint(4) NOT NULL default \'10\',
		  `who_send` enum(\'user\',\'group\',\'registered_user\') NOT NULL default \'group\',
		  `who_edit` enum(\'author\',\'author_group\',\'user\',\'group\') NOT NULL default \'author\',
		  `who_confirm` enum(\'author\',\'author_group\',\'user\',\'group\',\'no_body\') NOT NULL default \'no_body\',
		  `who_edit_comment_setting` enum(\'author\',\'author_group\',\'user\',\'group\') NOT NULL default \'author\',
		  `who_comment` enum(\'group\',\'registered_user\',\'every_body\',\'no_body\') NOT NULL default \'group\',
		  `who_confirm_comment` enum(\'author\',\'user\',\'group\',\'no_body\') NOT NULL default \'no_body\',
              `about` text NOT NULL,
              PRIMARY KEY  (`id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1'
		,
		'CREATE TABLE `#__news_comment` (
              `id` int(11) NOT NULL auto_increment,
              `store_id` int(11) NOT NULL default \'0\',
              `user_id` int(11) NOT NULL default \'0\',
              `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
              `username` varchar(200) NOT NULL default \'\',
              `user_agent` varchar(200) NOT NULL default \'\',
              `confirmed` enum(\'true\',\'false\') NOT NULL default \'true\',
              `title` varchar(255) NOT NULL default \'\',
              `content` text NOT NULL,
              PRIMARY KEY  (`id`),
              KEY `store_id` (`store_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1'
		,
		'CREATE TABLE `#__news_counter` (
              `news_id` int(11) NOT NULL default \'0\',
              `count` bigint(20) NOT NULL default \'0\',
              KEY `news_id` (`news_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1'
		,
		'CREATE TABLE `#__news_log` (
              `store_id` int(11) NOT NULL default \'0\',
              `user_id` int(11) NOT NULL default \'0\',
              `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
              `action` text NOT NULL,
              PRIMARY KEY  (`store_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1'
		,
		'CREATE TABLE `#__news_store` (
              `id` int(11) NOT NULL auto_increment,
              `news_id` int(11) NOT NULL default \'0\',
              `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
              `who_comment` enum(\'group\',\'registered_user\',\'every_body\',\'no_body\') NOT NULL default \'group\',
              `who_confirm_comment` enum(\'author\',\'user\',\'group\',\'no_body\') NOT NULL default \'no_body\',
              `confirmed` enum(\'true\',\'false\') NOT NULL default \'true\',
              `user_id` int(11) NOT NULL default \'0\',
              `title` varchar(255) NOT NULL default \'\',
              `content` mediumtext NOT NULL,
              `add_content` longtext NOT NULL,
              PRIMARY KEY  (`id`),
              KEY `news_id` (`news_id`)
            ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1'
		,
            'CREATE TABLE `#__news_store_backup` (
              `id` int(11) NOT NULL auto_increment,
              `news_id` int(11) NOT NULL default \'0\',
              `time` timestamp NOT NULL default CURRENT_TIMESTAMP,
              `who_comment` enum(\'group\',\'registered_user\',\'every_body\',\'no_body\') NOT NULL default \'group\',
              `who_confirm_comment` enum(\'author\',\'user\',\'group\',\'no_body\') NOT NULL default \'no_body\',
              `confirmed` enum(\'true\',\'false\') NOT NULL default \'true\',
              `user_id` int(11) NOT NULL default \'0\',
              `title` varchar(255) NOT NULL default \'\',
              `content` mediumtext NOT NULL,
              `add_content` longtext NOT NULL,
              PRIMARY KEY  (`id`),
              KEY `news_id` (`news_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1'
            ,
		'CREATE TABLE `#__news_user` (
              `user_id` int(11) NOT NULL default \'0\',
              `news_id` int(11) NOT NULL default \'0\',
              `last_time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
              `avator` varchar(255) NOT NULL default \'\',
              `posts` int(11) NOT NULL default \'0\',
              `about` varchar(255) NOT NULL default \'\',
              PRIMARY KEY  (`user_id`,`news_id`)
            ) ENGINE=MyISAM DEFAULT CHARSET=latin1'
		);
		
		$i = 0;
		foreach($queries as $query){
			$result[] = $lb['db']->query($query, array ());
			$return  &= $result[$i++]['result'];
		}
		return $return;
	}
	
	/**
	  * uninstall this page type
	  * 
	  * @author	Armin Borumand
	  * @return	boolean		return true if successfull uninstalled
	  */
	public function uninstall(){
		global $lb;
		
		$queries = array (
					'DROP TABLE `#__news`',
					'DROP TABLE `#__news_store`',
					'DROP TABLE `#__news_store_backup`',
					'DROP TABLE `#__news_user`',
					'DROP TABLE `#__news_comment`',
					'DROP TABLE `#__news_log`',
					'DROP TABLE `#__news_counter`'
				);
		
		$i = 0;
		foreach($queris as $query){
			$result[] = $lb['db']->query($query, array ());
			$return	 &= $result[$i++]['result'];
		}
		return $return;
	}
	
	/**
	 * search in pages
	 *
	 * @author	Armin Borumand
	 * @param	array		search words
	 * @param	int		limit start row
	 * @param	int		number of results
	 * @return	array		consist of page title and ids
	 */
	public function search(&$arr, $start, $number){
		global $lb;
		
		$conds = '';
		foreach($arr as $val){
			$params[] = array('%'.$val[1].'%', 'text');
			$conds .= 'CONCAT(title, content, add_content) like # '.$val[0].' ';
		}			
		$conds = substr($conds, 0, strlen($conds)-3);
			
		//Setting LIMIT ranges
		$params[] = array($start,	'int');
		$params[] = array($number,	'int');
		
		//double use!
		$params = array_merge($params, $params);
		array_pop($params);
		array_pop($params);
		
		$result = $lb['db']->query('SELECT id , news_id, title 
						FROM #__news_store 
							WHERE ' . $conds . 'LIMIT #,# 
						UNION SELECT count(id), NULL, NULL
						FROM #__news_store 
							WHERE ' . $conds, $params);
		if($result['num_of_rows'] < 1){
			$result['rows'] = array();
			return;
		}
		
		$num = $result['num_of_rows'] -1 ;
		if($num < $number){
			$number = $num;
		}
		
		$result['num_of_rows'] = intval($result['rows'][$number]['id']);
		array_pop($result['rows']);			
			
		if($num == 0){
			return $result;
		}
			
		for($i = 0; $i < $num; $i++){
			$ids[] = $result['rows'][$i]['id'];
			$news_ids[] = $result['rows'][$i]['news_id'];
		}
			
		$page_ids = lb_page::get_id($news_ids, 'news');

		for($i = 0; $i < $num; $i++){
			$result['rows'][$i]['id'] = $page_ids[$news_ids[$i]] . '&news_task=show&news_id=' . $ids[$i];
		}	

		
		return $result;		
	}

	/**
	 * Return number of pages or number of stored news
	 *
	 * @author	Armin Borumand
	 * @param		int news id
	 * @return	int	number of pages
	 */
	public function count($id=false){
		global $lb;
		
		if($id){
			$query = 'SELECT count(*) AS count FROM #__news_store WHERE news_id = #';
			$params = array(
						array($id, 'int')
						);
		}else{
			$query = 'SELECT count(*) AS count FROM #__news';
			$param = array();
		}
		
		$result = $lb['db']->query($query, $array);
		
		if($result['num_of_rows'] > 0){
			return $result['rows'][0]['count'];
		}else{
			return -1;
		}		
	}

	/**
	 * who can send news
	 *
	 * @author	Armin Borumand
	 * @return	string	who can send news
	 */
	public function who_send(){
		return $this->perms['who_send'];
	}
	
	/**
	 * who can confirm news
	 *
	 * @author	Armin Borumand
	 * @return	string	who can confirm news
	 */
	public function who_confirm(){
		return $this->perms['who_confirm'];
	}

	/**
	 * who can edit news
	 *
	 * @author	Armin Borumand
	 * @return	string	who can edit news
	 */
	public function who_edit(){
		return $this->perms['who_edit'];
	}
	
	/**
	 * who can edit comment setting
	 *
	 * @author	Armin Borumand
	 * @return	string	who can edit comment setting
	 */
	public function who_edit_comment_setting(){
		return $this->perms['who_edit_comment_setting'];
	}

	/**
	 * who can send comment
	 *
	 * @author	Armin Borumand
	 * @return	string	who can send comment
	 */
	public function who_comment(){
		return $this->perms['who_comment'];
	}

	/**
	 * who can send comment
	 *
	 * @author	Armin Borumand
	 * @return	string	who can confirm comments
	 */
	public function who_confirm_comment(){
		return $this->perms['who_confirm_comment'];
	}

	/**
	 * can send news or not
	 *
	 * @author	Armin Borumand
	 * @return	boolean	true if can send and false if can't
	 */
	public function can_send(){
		global $lb;
		$return = false;

		if($lb['user']->is_moderator() || $lb['user']->is_su()){
			return true;
		}

		switch($this->perms['who_send']){
			case 'user':
				if($lb['user']->user_id() == $this->user_id){
					$return = true;
				}
				break;
			case 'group':
				if($lb['user']->group_id() == $this->user_group['id']){
					$return = true;
				}
				break;
			case 'registered_user':
				if($lb['user']->is_user()){
					$return = true;
				}
				break;
		}
		
		return $return;
	}

	/**
	 * can edit news or not
	 *
	 * @author	Armin Borumand
	 * @return	boolean	true if can edit and false if can't
	 */
	public function can_edit(){
		global $lb;
		$return = false;

		if($lb['user']->is_moderator() || $lb['user']->is_su()){
			return true;
		}

		switch($this->perms['who_confirm_comment']){
			case 'user':
				if($lb['user']->user_id() == $this->user_id){
					$return = true;
				}
				break;
			case 'author_group':
			case 'group':
				if($lb['user']->group_id() == $this->user_group['id']){
					$return = true;
				}
				break;
		}
		return $return;
	}
	
	/**
	 * can edit comment setting or not
	 *
	 * @author	Armin Borumand
	 * @return	boolean	true if can edit comment setting and false if can't
	 */
	public function can_edit_comment_setting(){
		global $lb;
		$return = false;

		if($lb['user']->is_moderator() || $lb['user']->is_su()){
			return true;
		}

		switch($this->perms['who_edit']){
			case 'user':
				if($lb['user']->user_id() == $this->user_id){
					$return = true;
				}
				break;
			case 'author_group':
			case 'group':
				if($lb['user']->group_id() == $this->user_group['id']){
					$return = true;
				}
				break;
		}
		return $return;
	}
	
	/**
	 * can confirm news or not
	 *
	 * @author	Armin Borumand
	 * @return	boolean	true if can confirm and false if can't
	 */
	public function can_confirm(){
		global $lb;
		$return = false;

		if($lb['user']->is_moderator() || $lb['user']->is_su()){
			return true;
		}

		switch($this->perms['who_confirm']){
			case 'user':
				if($lb['user']->user_id() == $this->user_id){
					$return = true;
				}
				break;
			case 'author_group':
			case 'group':
				if($lb['user']->group_id() == $this->user_group['id']){
					$return = true;
				}
				break;
			case 'no_body':
				$return = true;
				break;
		}

		return $return;
	}
	
	/**
	 * confirm sended news
	 *
	 * @author	Armin Borumand
	 * @return	boolean	if don't need confirmation(no_body) return true otherwise return false
	 */
	public function check_confirm(){
		global $lb;
		
		if($this->perms['who_confirm'] == 'no_body'){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * About news
	 *
	 * @author	Armin Borumand
	 * @return	string	about
	 */
	public function about(){
		return $this->about;
	}
	
	/**
	 * Filter input text from html tags
	 *
	 * @author	Armin Borumand
	 * @param		string	input text
	 * @param		string	clean text
	 */
	public function html_filter(&$string){
		//html allowable tags
		$allowable = array('<br>', '<a>', '<p>', '<div>', '<b>', '<strike>', '<u>', '<em>', '<strong>'
					     , '<blockquote>', '<sup>', '<sub>', '<ul>', '<ol>', '<li>', '<table>', '<tr>', '<td>'
						 , '<tbody>', '<img>');
		return lb_system::strip_tags($string, $allowable);
	}
}
